<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\Notice;
use plugin\admin\app\model\UserNotice;

class NoticeService
{
    public static function list($page, $length = 10, $type = Notice::TYPE_SYSTEM_NOTICE)
    {
        $offset = ($page - 1) * $length;
        $totalCount = Notice::count();
        $notices = Notice::select(['id', 'title', 'content', 'desc', 'created_time'])->orderByDesc('created_time')->offset($offset)->limit($length)->get()->toArray();


        $userId = get_user_id();
        if ($userId) {
            $noticeIds = array_column($notices, 'id');

            $userNotice = UserNotice::whereIn('notice_id', $noticeIds)->where('user_id', $userId)->get()->toArray();
            $userNotice = array_combine(
                array_column($userNotice, 'notice_id'),
                array_values($userNotice)
            );

            foreach ($notices as $key=>$notice) {
                $notices[$key]['is_read'] = isset($userNotice[$notice['id']]);
                $notices[$key]['read_time'] = isset($userNotice[$notice['id']]) ? $userNotice[$notice['id']]['created_time'] : '';
                $notices[$key]['content'] = strip_tags($notice['content']);
            }
        }

        return Page::wrap($totalCount, $page, $length, $notices);
    }

    public static function unreadCount()
    {
        $userId = get_user_id();

        $totalCount = Notice::count();
        $notices = Notice::select(['id'])->get()->toArray();
        $noticeIds = array_column($notices, 'id');

        $readCount = UserNotice::where('user_id', $userId)->whereIn('notice_id', $noticeIds)->count();

        return $totalCount - $readCount;
    }

    public static function getLatestNotice()
    {
        $systemNotice = SystemNoticeService::latestMessage();
        $officalNotice = Notice::select(['id', 'title', 'content', 'desc', 'created_time'])->orderByDesc('created_time')->first();

        return [$systemNotice, $officalNotice];
    }

    public static function markAllRead()
    {
        $userId = get_user_id();
        $userNotice = UserNotice::where('user_id', $userId)->get()->toArray();
        $readNoticeIds = array_column($userNotice, 'notice_id');

        $notices = Notice::whereNotIn('id', $readNoticeIds)->get()->toArray();

        $insertData = [];
        $currentDatetime = date('Y-m-d H:i:s');
        foreach ($notices as $key=>$notice) {
            $insertData[] = [
                'user_id' => $userId,
                'notice_id' => $notice['id'],
                'created_time' => $currentDatetime,
            ];
        }

        UserNotice::insert($insertData);
    }

    public static function detail($id)
    {
        $notice = Notice::find($id);

        if (! $notice) {
            throw new \Exception('不存在的公告');
        }

        $notice['content'] = str_replace('<img src="', '<img src="' . getenv('APP_URL'), $notice['content']);

        if (UserNotice::where('notice_id', $id)->where('user_id', get_user_id())->count() == 0) {
            UserNotice::insert([
                'user_id' => get_user_id(),
                'notice_id' => $id,
                'created_time' => date('Y-m-d H:i:s')
            ]);
        }

        return $notice;
    }

}